pimpas.Log = Class.create( );

pimpas.Extends(pimpas.Log.prototype, pimpas.Object);
pimpas.Extends(pimpas.Log.prototype, pimpas.ListenerSupport.prototype);
pimpas.Extends(pimpas.Log.prototype,
   {
		message: null,
		initialize: function() {
			this.message = new Array();
			pimpas.Log.add(this);
			this.id=pimpas.globalID++;
			this.listeners = new Array();
		},
		log: function(level, msg) {
			var obj = [level, msg, new Date(), this.log.caller];
			this.message.push(obj);
			this.callListeners(this.returnMessage(obj));
		},
		debug: function(msg) {
			this.log(pimpas.Log.DEBUG, msg);
		},
		info: function(msg) {
			this.log(pimpas.Log.INFO, msg);
		},
		warning: function(msg) {
			this.log(pimpas.Log.WARN, msg);
		},
		error: function(msg) {
			this.log(pimpas.Log.ERROR, msg);
		},
		fatal: function(msg) {
			this.log(pimpas.Log.FATAL, msg);
		},
		flush: function() {
			var msg = this.message;
			if(arguments.length > 0)
				msg = arguments[0];
			var a = "";
			while(msg.length > 0)
				a += msg.shift().join("=>");
			return a;
		},
		flushByLevel: function(lvl) {
			var ar = new Array();
			for(var i=0;i<this.message.length;i++)
				if(this.message[i][0] == lvl)	
					ar.push(this.message[i]);
					
			return this.flush( ar );
		},
		pop: function() {
			if(this.message.length > 0) {
				var o = this.message.shift();
				return this.returnMessage(o);
			}
			
			return null;
		},
		returnMessage: function(o) {
				return {level: o[0], message: o[1], time: o[2], owner: o[3]};
		},
		popByLevel: function(lvl) {
			for(var i=0;i<this.message.length;i++) {
				if(this.message[i][0] == lvl)
					return this.returnMessage(this.message.remove(this.message[i]));		
			}
			return null;
		},
		hasMessage: function() {
			return this.message.length>0;
		},
		toSource: function() {
			return this.message;	
		},
		callListeners: function() {
			var ar = new Array();
			ar.push(this);
			
			for(var i=0;i<arguments.length;i++) ar.push(arguments[i]);
			
	 		for(var i=0;i<this.listeners.length;i++)
				this.listeners[i].callBack.apply(this.listeners[i], ar);
				
			for(i=0;i<pimpas.Log.globalListeners.length;i++)
				pimpas.Log.globalListeners[i].callBack.apply(pimpas.Log.globalListeners[i], ar);
		}
   }
);

pimpas.Extends(pimpas.Log, 
	{
		DEBUG: "[DEBUG]",
		INFO: "[INFO]",
		WARNING: "[WARNING]",
		ERROR: "[ERROR]",
		FATAL: "[FATAL]"
	}
);

pimpas.Extends(pimpas.Log,
	{
		instances: new Array(),
		add: function(obj) {
			this.instances.push(obj);
		},
		globalListeners: new Array(),
		addGlobalListener: function(l) {
			if(l instanceof pimpas.Listener)
				this.globalListeners.push(l);
		}
	}
);